#!/usr/bin/env python3
import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk
import json,os
from multiprocessing import Process
class aStatusIcon:
    def __init__(self):
        self.statusicon = Gtk.StatusIcon()
        self.statusicon.set_from_file(os.path.join(os.getenv("HOME"),'config/myctl/stop.png')) 
        self.statusicon.connect("popup-menu", self.right_click_event)
        self.statusicon.set_tooltip_text("Control Web Server")
        #window = Gtk.Window()
        #window.connect("destroy", lambda w: Gtk.main_quit())
        #window.show_all()
        fjson1 = os.path.join(os.getenv("HOME"),"config/myctl/app.json")
        fp = open(fjson1,'r')
        if fp is not None:
            data = fp.read()
            fp.close()
        json1 = json.loads(data)
        self.exec1 = json1["exec"]
        self.p = None
        
        self.menu = Gtk.Menu()

        self.run1 = Gtk.MenuItem()
        self.run1.set_label("Run")
        quit1 = Gtk.MenuItem()
        quit1.set_label("Quit")

        self.run1.connect("activate", self.run_server)
        quit1.connect("activate", self.quit_app)

        self.menu.append(self.run1)
        self.menu.append(quit1)
        
        self.menu.show_all()

    def right_click_event(self, icon, button, time):
        #menu.popup(None, None, gtk.status_icon_position_menu, button, time, self.statusicon) # previous working pygtk line
        self.menu.popup(None, None, None, Gtk.StatusIcon.position_menu, button, time) #i assume this is problem line

    def run_server(self, widget):
        self.menu.popdown()
        if self.p==None or self.p.is_alive() is False:
            self.p = Process(target=self.child_run_server)
            self.p.start()
            self.statusicon.set_from_file(os.path.join(os.getenv("HOME"),'config/myctl/run.png')) 
            self.run1.set_label("Stop")
        else:
            self.stop_server(widget)
        return
    def stop_server(self,widget):
        if self.p is not None and self.p.is_alive():
            self.p.terminate()
            self.statusicon.set_from_file(os.path.join(os.getenv("HOME"),'config/myctl/stop.png')) 
            self.run1.set_label("Run")
        return
    def quit_app(self,widget):
        self.stop_server(widget)
        Gtk.main_quit()
    def child_run_server(self):
        os.execl(self.exec1,self.exec1)
        return
aStatusIcon()
Gtk.main()
